package com.photo.photePro.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.photo.photePro.common.R;
import com.photo.photePro.entity.Contestant;
import com.photo.photePro.entity.User;
import com.photo.photePro.service.ContestantService;
import com.photo.photePro.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 参赛选手Controller
 */
@Slf4j
@RestController
@RequestMapping("/contestants")
public class ContestantController {

    @Autowired
    private ContestantService contestantService;

    @Autowired
    private UserService userService;

    /**
     * 分页查询参赛选手
     */
    @GetMapping("/page")
    public R<Page<Contestant>> page(
            @RequestParam(defaultValue = "1") int page, 
            @RequestParam(defaultValue = "10") int pageSize, 
            @RequestParam(required = false) String realName, 
            @RequestParam(required = false) Integer status) {
        log.info("分页查询参赛选手：page = {}, pageSize = {}, realName = {}, status = {}", page, pageSize, realName, status);
        
        Page<Contestant> pageInfo = contestantService.pageQuery(page, pageSize, realName, status);
        log.info("查询结果：total = {}, records size = {}", pageInfo.getTotal(), pageInfo.getRecords().size());
        
        return R.success(pageInfo);
    }

    /**
     * 根据ID查询参赛选手详情
     */
    @GetMapping("/{id}")
    public R<Contestant> getById(@PathVariable Long id) {
        log.info("查询参赛选手详情：id = {}", id);
        
        Contestant contestant = contestantService.getById(id);
        if (contestant != null) {
            return R.success(contestant);
        }
        return R.error("参赛选手不存在");
    }
    
    /**
     * 根据用户ID查询参赛选手
     */
    @GetMapping("/user/{userId}")
    public R<Contestant> getByUserId(@PathVariable Long userId) {
        log.info("根据用户ID查询参赛选手：userId = {}", userId);
        
        Contestant contestant = contestantService.getByUserId(userId);
        return R.success(contestant);
    }

    /**
     * 报名参赛
     */
    @PostMapping
    public R<String> save(@RequestBody Contestant contestant) {
        log.info("报名参赛：contestant = {}", contestant);
        
        // 检查用户是否已经报名
        Contestant exist = contestantService.getByUserId(contestant.getUserId());
        if (exist != null) {
            return R.error("您已经报名参赛，请勿重复提交");
        }
        
        // 设置初始状态和时间
        contestant.setStatus(0);  // 待审核
        contestant.setCreateTime(LocalDateTime.now());
        contestant.setUpdateTime(LocalDateTime.now());
        
        contestantService.save(contestant);
        return R.success("报名成功，请等待审核");
    }
    
    /**
     * 无需登录的参赛报名
     */
    @PostMapping("/register")
    public R<Map<String, String>> registerWithoutLogin(@RequestBody Contestant contestant) {
        log.info("无需登录报名参赛：contestant = {}", contestant);
        
        // 检查身份证号和手机号是否已经报名
        boolean exists = contestantService.checkExistsByIdCardOrPhone(contestant.getIdCard(), contestant.getPhone());
        if (exists) {
            return R.error("该身份证号或手机号已报名，请勿重复提交");
        }
        
        // 设置初始状态和时间
        contestant.setStatus(0);  // 待审核
        contestant.setCreateTime(LocalDateTime.now());
        contestant.setUpdateTime(LocalDateTime.now());
        
        // 生成唯一的报名编号
        String registrationNumber = generateRegistrationNumber();
        contestant.setRegistrationNumber(registrationNumber);
        
        // 保存报名信息
        contestantService.save(contestant);
        User user = new User();
        user.setUsername(contestant.getRealName());
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        user.setPassword(password);
        user.setRole(3);//表示是参赛者
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setNickname("参赛者");
        user.setEmail(contestant.getEmail());
        user.setPhone(contestant.getPhone());
        userService.save(user);

        // 返回报名编号
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("registrationNumber", registrationNumber);
        
        return R.success(resultMap);
    }

    /**
     * 生成唯一的报名编号
     */
    private String generateRegistrationNumber() {
        // 格式: CP + 年月日 + 4位随机数
        LocalDateTime now = LocalDateTime.now();
        String dateStr = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        int random = 1000 + new Random().nextInt(9000); // 1000-9999之间的随机数
        
        return "CP" + dateStr + random;
    }

    /**
     * 更新参赛信息
     */
    @PutMapping
    public R<String> update(@RequestBody Contestant contestant) {
        log.info("更新参赛信息：contestant = {}", contestant);
        
        // 只允许更新状态为待审核或已拒绝的记录
        Contestant exist = contestantService.getById(contestant.getId());
        if (exist == null) {
            return R.error("参赛记录不存在");
        }
        
        if (exist.getStatus() == 1) {
            return R.error("审核已通过的报名信息不能修改");
        }
        
        contestant.setStatus(0);  // 更新后重新置为待审核
        contestant.setUpdateTime(LocalDateTime.now());
        
        contestantService.updateById(contestant);
        return R.success("更新成功");
    }

    /**
     * 审核参赛选手
     */
    @PutMapping("/audit")
    public R<String> audit(Long id, Integer status, String rejectReason) {
        log.info("审核参赛选手：id = {}, status = {}, rejectReason = {}", id, status, rejectReason);
        
        if (id == null || status == null) {
            return R.error("参数错误");
        }
        
        boolean result = contestantService.audit(id, status, rejectReason);
        if (result) {
            return R.success("审核成功");
        }
        return R.error("审核失败");
    }

    /**
     * 取消参赛
     */
    @DeleteMapping("/{id}")
    public R<String> delete(@PathVariable Long id) {
        log.info("取消参赛：id = {}", id);
        
        contestantService.removeById(id);
        return R.success("取消成功");
    }
} 